"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能
Case Name   : xml配置参数开启共享存储开关,不指定dss共享卷名,合理报错
Create At   : 2023/04/20
Owner       : opentestcase043
Description :
        1.下载解压数据库包
        2.配置xml文件(1主1备),不指定dss共享卷名
        3.执行gs_preinstall
        4.清理环境
Expect      :
        1.成功
        2.成功
        3.合理报错
        4.清理环境成功
History     :
"""

import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from yat.test import macro
from yat.test import Node

LOG = Logger()
Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorage(unittest.TestCase):
    def setUp(self):
        LOG.info('-----this is setup-----')
        LOG.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_root_node = Node('PrimaryRoot')
        self.pri_node = Node('PrimaryDbUser')
        self.sta1_root_node = Node('Standby1Root')
        self.sta1_node = Node('Standby1DbUser')
        self.con = Constant()
        self.com = Common()
        self.u_name = 'ss_dms_xml_0002'
        self.instance_path = macro.DB_INSTANCE_PATH
        for num in range(macro.DB_INSTANCE_PATH.count('/') - 1):
            self.instance_path = os.path.dirname(self.instance_path)
        self.dir_path = os.path.join(self.instance_path, self.u_name)
        self.package_path = os.path.join(self.dir_path, 'pkg')
        self.conf_path = os.path.join(self.dir_path, 'config')
        self.data_path = os.path.join(self.dir_path, 'cluster')
        self.xml_path = os.path.join(self.conf_path, 'ss_primary_standby.xml')
        self.env_path = os.path.join(self.conf_path, 'env')

    def test_share_storage(self):
        text = '-----step1:下载解压数据库包; expect:成功-----'
        LOG.info(text)
        self.com.check_load_msg(self.pri_root_node, self.pri_node,
                                self.package_path, self.conf_path)
        pri_node_name = self.com.get_sh_result(self.pri_root_node,
                                               "uname -n")
        self.assertIsNotNone(pri_node_name, 'pri_node_name获取失败')
        sta1_node_name = self.com.get_sh_result(self.sta1_root_node,
                                               "uname -n")
        self.assertIsNotNone(sta1_node_name, 'sta_node_name获取失败')
        LOG.info('-----查询系统未使用端口-----')
        port_list = []
        for i in range(65535):
            port = self.com.get_not_used_port(self.pri_node)
            self.assertNotEqual(0, port, '端口获取失败')
            if port not in port_list and len(port_list) < 2:
                port_list.append(port)
            elif len(port_list) >= 2:
                break

        text = '-----step2:配置xml文件(1主1备),指定共享存储相关全部参数; ' \
               'expect:成功-----'
        LOG.info(text)
        gaussdb_app_path = os.path.join(self.data_path, 'app')
        tmpmppdb_path = os.path.join(self.data_path, 'tmp')
        gaussdb_tool_path = os.path.join(self.data_path, 'tool')
        gaussdbLogPath = os.path.join(self.data_path, 'log')
        script_path = os.path.join(self.package_path, 'script')
        data_node1 = os.path.join(self.data_path, 'dn1')
        cmDir = os.path.join(self.data_path, 'cm')
        self.com.scp_file(self.pri_root_node, 'ss_primary_standby.xml',
                          self.conf_path)
        xml_cmd = f"sed -i 's#v_nodeNames#{pri_node_name},{sta1_node_name}" \
                  f"#g' {self.xml_path};" \
                  f"sed -i 's#v_master#{pri_node_name}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_gaussdbAppPath#{gaussdb_app_path}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_gaussdbLogPath#{gaussdbLogPath}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_db_host#{self.pri_node.db_host}," \
                  f"{self.sta1_node.db_host}#g' {self.xml_path};" \
                  f"sed -i 's#v_tmpMppdbPath#{tmpmppdb_path}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_gaussdbToolPath#{gaussdb_tool_path}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_corePath#{macro.DB_CORE_PATH}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_dss_home#{macro.DSS_HOME}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_shareDiskDir#{macro.SHARE_DISK_DIR}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_dss_vg_info#{macro.DSS_VG_INFO}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i '/v_ss_dss_vg_name/d' {self.xml_path};" \
                  f"sed -i 's#v_votingDiskPath#{macro.VOTING_DISK_PATH}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_pri_nodeNames#{pri_node_name}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_pri_db_host#{self.pri_node.db_host}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_cmServerPortBase#{port_list[0]}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_cmServerListenIp1#{self.pri_node.db_host}," \
                  f"{self.sta1_node.db_host}#g' {self.xml_path};" \
                  f"sed -i 's#v_cmServerHaIp1#{self.pri_node.db_host}," \
                  f"{self.sta1_node.db_host}#g' {self.xml_path};" \
                  f"sed -i 's#v_cmServerRelation#{pri_node_name}," \
                  f"{sta1_node_name}#g' {self.xml_path};" \
                  f"sed -i 's#v_dataPortBase#{port_list[1]}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_dataNode1#{data_node1},{sta1_node_name}," \
                  f"{data_node1}#g' {self.xml_path};" \
                  f"sed -i 's#v_sta_nodeNames#{sta1_node_name}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_sta_db_host#{self.sta1_node.db_host}#g' " \
                  f"{self.xml_path};" \
                  f"sed -i 's#v_cmDir#{cmDir}#g' " \
                  f"{self.xml_path};" \
                  f"cat {self.xml_path}"
        LOG.info(xml_cmd)
        result = self.com.get_sh_result(self.pri_root_node, xml_cmd)
        LOG.info(result)
        msg_list = [gaussdb_app_path, gaussdbLogPath, tmpmppdb_path,
                    gaussdb_tool_path, macro.DB_CORE_PATH, macro.DSS_VG_INFO,
                    macro.DSS_HOME, macro.SHARE_DISK_DIR,
                    macro.VOTING_DISK_PATH, pri_node_name,
                    self.pri_node.db_host, self.pri_node.db_host,
                    str(port_list[0]), str(port_list[1]), sta1_node_name,
                    self.sta1_node.db_host]
        for msg in msg_list:
            self.assertIn(msg, result, '执行失败:' + text)

        LOG.info('-----step3:创建用户并修改文件属性; expect:成功-----')
        LOG.info(text)
        self.com.create_user(self.pri_root_node, self.u_name)
        self.com.create_user(self.sta1_root_node, self.u_name)
        cmd = f'chown -R {self.u_name}:{self.u_name} {self.dir_path}'
        LOG.info(cmd)
        status = self.pri_root_node.sh(cmd).result()
        LOG.info(status)
        self.assertEqual('', status, '执行失败:' + text)

        LOG.info('-----step4:执行gs_preinstall; expect:合理报错-----')
        preinstall_cmd = f"./gs_preinstall -U {self.u_name} -G {self.u_name} " \
            f"-X {self.xml_path} --sep-env-file={self.env_path} " \
            f"--skip-hostname-set --non-interactive;"
        execute_cmd = f'''cd {script_path}
                                expect <<EOF
                                set timeout 300
                                spawn {preinstall_cmd}
                                expect "*(yes/no)?"
                                send "yes\\n"
                                expect "Password:"
                                send "{self.pri_root_node.ssh_password}\\n"
                                expect "*(yes/no)?"
                                send "yes\\n"
                                expect "Password:"
                                send "{macro.COMMON_PASSWD}\\n"
                                expect eof\n''' + '''EOF'''
        LOG.info(execute_cmd)
        status = self.pri_root_node.sh(execute_cmd).result()
        LOG.info(status)
        self.assertIn("The parameter 'dss_vgname' value can't be empty", status,
                      '执行失败:' + text)

    def tearDown(self):
        LOG.info('-----this is tearDown-----')
        text = '-----step5:清理环境; expect:清理环境成功-----'
        LOG.info(text)
        text1 = '-----删除用户下进程-----'
        LOG.info(text1)
        cmd = f"ps -u {self.u_name} | grep -v PID| " \
                   f"awk \'{{{{print $1}}}}\' | xargs kill -9;" \
                   f"ipcs -m|grep {self.u_name}|tr -s ' '|cut -d ' ' -f 2" \
                   f" | xargs -I {{{{}}}} ipcrm -m {{{{}}}};" \
                   f"ipcs -s|grep {self.u_name}|tr -s ' '|cut -d ' ' -f 2" \
                   f" | xargs -I {{{{}}}} ipcrm -s {{{{}}}};sync;" \
                   f"echo 3 > /proc/sys/vm/drop_caches"
        LOG.info(cmd)
        self.com.get_sh_result(self.pri_root_node, cmd)
        self.com.get_sh_result(self.sta1_root_node, cmd)

        text2 = '-----删除用户-----'
        LOG.info(text2)
        cmd = f'if id -u {self.u_name} >/dev/null 2>&1;' \
              f'then userdel -rf {self.u_name}; fi'
        LOG.info(cmd)
        status1 = self.com.get_sh_result(self.pri_root_node, cmd)
        status2 = self.com.get_sh_result(self.sta1_root_node, cmd)

        text3 = '-----删除数据目录-----'
        LOG.info(text3)
        cmd = f'rm -rf {self.dir_path}'
        self.com.get_sh_result(self.pri_root_node, cmd)
        cmd = f'if [ -d {self.dir_path} ]; ' \
              f'then echo "exists"; else echo "not exists"; fi'
        status3 = self.com.get_sh_result(self.pri_root_node, cmd)
        status4 = self.com.get_sh_result(self.pri_root_node, cmd)

        self.assertEqual('', status1, '执行失败:' + text2)
        self.assertEqual('', status2, '执行失败:' + text2)
        self.assertEqual('not exists', status3, '执行失败:' + text3)
        self.assertEqual('not exists', status4, '执行失败:' + text3)
        LOG.info(f'-----{os.path.basename(__file__)} end-----')
